package com.example.cash.craft.config;

import com.example.cash.craft.security.CustomAuthenticationEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableMethodSecurity
public class SecurityConfiguration {

    @Autowired
    private CustomAuthenticationEntryPoint authenticationEntryPoint;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 配置白名单
        String[] permitUrls = new String[]{
                "/doc.html", // Knife4j相关文件
                "/webjars/**", // Knife4j相关文件
                "/v3/api-docs/**", // Knife4j相关文件
                "/favicon.ico", // Knife4j相关文件
                "/api/user/register", // 用户注册接口
                "/api/passport/login", // 用户登录接口
                "/api/category/{id}", // 根据ID查询类别接口
                "/api/category", // 查询类别列表接口
                "/api/product/{id}", // 根据ID查询商品接口
                "/api/product", // 查询商品列表接口
        };

        // 配置权限控制
        http.authorizeHttpRequests(authorize -> authorize
                .requestMatchers(permitUrls).permitAll().anyRequest().authenticated());

        // 配置认证失败处理器（响应未登录的错误信息）
        http.exceptionHandling(exceptionHandling -> exceptionHandling.authenticationEntryPoint(authenticationEntryPoint));

        // 禁用CSRF（防止伪造跨域攻击的机制）
        http.csrf(csrf -> csrf.disable());

        // 不需要显式的保存认证信息
        http.securityContext(securityContext -> securityContext.requireExplicitSave(false));

        // 禁用表单登录
        http.formLogin(formLogin -> formLogin.disable());

        return http.build();
    }

}
